var ns, app, dialog, toast,imageBrowser;
app = new Vue({
    el: '#app',
    data: {
        MeetRoomID: 0,
        ProjectID: 0,
        ID: 0,
        meetform: {},
        MeetingItemList: [],
        ImgList: [],
        //新增
        form: {
            MeetingTitle: '',
            MeetTime: '',
            MeetingApplyPhone: '',
            ReservationDate: '',
            StartTime: '',
            EndTime: '',
            MeetingPeopleNum: 1,
            Descriotion: '',
            Remark: '',
            ServiceList: [],
            ItemList: [],
            ItemListIDs: [],
        },
        //预约时段
        ChooseCount: 0,
        IsShowTime: false,
        TimeList: [],
        dayModel: {},
        dayList: [],
        ReservationList: [],
        SelectTime: '',
        showSelectTime:'',
        ChooseStartModel: {},
        ChooseEndModel: {},
        CalculateTimeDesc: '',//时长
        //会议服务
        IsShowService: false,
        ServiceList: [],
        TotalPrice:0,
        //临时物品
        IsShowItem: false,
        ItemList: [],
    },
    methods: {
        //图片预览
        img_browser: function (itemurl, url) {
            var that = this;
            var imgurls = [];
            imgurls.push(url);
            imageBrowser.openImages({
                imageUrls: imgurls,
                showList: false,
                activeIndex: 0
            });
        },
        get_data: function () {
            var that = this;
            ns.post({
                action: 'getmeetingroomdetail',
                RoomID: that.MeetRoomID,
            }, function (succeed, data, err) {
                if (succeed) {
                    that.meetform = data.MeetingRoomInfo;
                    that.ImgList = data.MeetingRoomFileList || [];
                    that.MeetingItemList = data.MeetingItemList || [];

                    that.getDate();//获取预约时间
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
            })
        },
        get_data_item: function () {
            var that = this;
            ns.post({
                action: 'getmeetingitemlist',
                ProjectID: that.ProjectID,
            }, function (succeed, data, err) {
                if (succeed) {
                    var data = data.MeetingItemList || [];
                    data = data.map((item) => {
                        item.IsSelected = false;
                        return item;
                    });
                    that.ItemList = data;
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
            })
        },
        get_data_service: function () {
            var that = this;
            ns.post({
                action: 'getmeetingservicelist',
                ProjectID: that.ProjectID,
            }, function (succeed, data, err) {
                if (succeed) {
                    var data = data.MeetingServicesList || [];
                    data = data.map((item) => {
                        item.Number = 0;
                        return item;
                    });
                    that.ServiceList = data;
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
            })
        },
        //预约时段选择
        getDate: function () {
            var that = this;
            var newdayList = [];
            var LenTime = 7;
            for (var i = 0; i < LenTime; i++) {
                var nowDate = moment().add(i, 'days').format("YYYY-MM-DD");
                const weeknumber = moment(nowDate).day();//获取阿拉伯数字星期
                let weeks = weeknumber == 0 ? 7 : weeknumber;
                var dayDate = { ID: i + 1, Title: '今天', Week: '', Date: nowDate, MomentDate: '', WeekNumber: weeks };
                dayDate.MomentDate = moment(nowDate).format("MM月DD日");
                dayDate.Week = that.getweekday(nowDate);
                dayDate.Title = '周' + dayDate.Week;
                if (i == 0) {
                    dayDate.Title = '今日';
                }
                if (i == 1) {
                    dayDate.Title = '明日';
                }
                newdayList.push(dayDate);
            }

            that.dayList = newdayList;
            that.onDayChoose(that.dayList[0]);//初始化
        },
        getweekday: function (date) {
            var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
            var week = weekArray[new Date(date).getDay()];//注意此处必须是先new一个Date
            return week;
        },
        onDayChoose(item) {
            //选择日期
            var that = this;
            that.dayModel = item;
            that.form.ReservationDate = that.dayModel.Date;
            that.SelectTime = that.dayModel.Date;
            that.showSelectTime = moment(that.dayModel.Date).format("MM/DD");
            that.get_data_time();
        },
        get_data_time() {
            //根据日期加载时间 getmeetingroomappointment
            var that = this;
            ns.post({
                action: 'getmeetingroomappointment',
                RoomID: that.MeetRoomID,
                AppointmentDate: that.SelectTime,
            }, function (succeed, data, err) {
                if (succeed) {
                    that.ReservationList = data.AppointmentList || [];
                    that.onDealTime();
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
            })
        },
        onDealTime() {
            var that = this;
            var nowDate = moment(that.SelectTime).format("YYYY/MM/DD");
            var time1 = new Date(nowDate + ' ' + that.meetform.OpenStarTime);
            var time2 = new Date(nowDate + ' ' + that.meetform.OpenEndTime);
            var diffhours = moment(time2).diff(moment(time1), 'minutes');
            var JGHours = 15;//相差15分钟
            var numberdiff = Math.ceil(diffhours / JGHours)
             //判断是否整除
            if (diffhours % JGHours === 0) {
                numberdiff = numberdiff + 1;
            }
            var list = [];
            for (var i = 0; i < numberdiff; i++) {
                var model = { ID: i + 1, time: '', timetitle: '', endtime: '', endtimetitle: '', status: -1, tiptime: '', tipendtime: '', nowDate: nowDate, showtime: false, IsOpen: false };
                let startOfDay = time1;
                model.time = moment(startOfDay).add(i * JGHours, 'minutes').format("YYYY/MM/DD HH:mm:ss");
                model.endtime = moment(startOfDay).add((i + 1) * JGHours, 'minutes').format("YYYY/MM/DD HH:mm:ss");
                model.timetitle = moment(model.time).format("HH:mm");
                model.endtimetitle = moment(model.endtime).format("HH:mm");
                if (i == (numberdiff - 1)) {
                    model.endtime = moment(time2).format("YYYY/MM/DD HH:mm:ss");
                    model.endtimetitle = that.meetform.OpenEndTime;
                }
                if (that.ReservationList.length > 0) {
                    var returnStatus = that.onReturnSattus(that.ReservationList, model.time, model.endtime, model);
                    model.status = returnStatus;
                }
                //显示间隔两个小时
                var diffshow = moment(time1).diff(moment(model.time), 'minutes');
                if (diffshow % 120 == 0) {
                    model.showtime = true;
                }
                //判断是否过期 与当前时间判断
                var diffminutes = moment().diff(moment(nowDate + ' ' + model.timetitle), 'minutes');
                if (diffminutes > 0) {
                    model.status = -2;
                }
                list.push(model);
            }
            that.TimeList = list;
        },
        onReturnSattus(data, starttime, endtime, model) {
            var that = this;
            var returnStatus = -1;
            var starttimes = moment(starttime);
            var endtimes = moment(endtime);
            data.forEach((item, index, array) => {
                if (Number(that.MeetRoomID) != Number(item.ID) && item.Status < 2) {
                    var diffdate = moment(item.ReservationDate).format("YYYY/MM/DD");
                    var difftime1 = new Date(diffdate + ' ' + item.ReservationStartTime);
                    var difftime2 = new Date(diffdate + ' ' + item.ReservationEndTime);
                    var date1 = moment(difftime1);
                    var date2 = moment(difftime2);
                    const isBetween = starttimes.isBetween(date1, date2, null, '[)');
                    const isBetween2 = endtimes.isBetween(date1, date2, null, '(]');
                    if (isBetween || isBetween2) {
                        returnStatus = item.Status;
                        model.tiptime = item.ReservationStartTime;
                        model.tipendtime = item.ReservationEndTime;
                    }
                }
            })
            return returnStatus;
        },
        doOpenChooseTime() {
            this.IsShowTime = !this.IsShowTime;
        },
        doOpenChooseTimeCancel() {
            var that = this;
            that.ChooseCount = 0;
            that.form.StartTime = '';
            that.form.EndTime = '';
            that.ChooseStartModel = {};
            that.ChooseEndModel = {};
            that.CalculateTimeDesc = "";
            that.TimeList.forEach((itemt, indext, arrayt) => {
                itemt.IsOpen = false;
            });
        },
        onDayChooseTime(item) {
            var that = this;
            if (item.status != -1) {
                return;
            }
            if (that.ChooseStartModel.timetitle != undefined && that.ChooseEndModel.timetitle != undefined) {
                that.doOpenChooseTimeCancel();
            }
            if (that.ChooseCount == 0) {
                that.form.StartTime = item.timetitle;
                that.ChooseStartModel = item;
                item.IsOpen = true;
            }
            if (that.ChooseCount == 1) {
                that.form.EndTime = item.timetitle;
                that.ChooseEndModel = item;
            }
            that.ChooseCount++;
            //设置选中 判断选择区间必须是空闲
            if (that.ChooseStartModel.timetitle != undefined && that.ChooseEndModel.timetitle != undefined) {
                that.TimeList.forEach((itemt, indext, arrayt) => {
                    itemt.IsOpen = false;
                    if (that.ChooseStartModel.ID <= itemt.ID && itemt.ID <= that.ChooseEndModel.ID) {
                        if (itemt.status == -1) {
                            itemt.IsOpen = true;
                        }
                        if (itemt.status != -1) {
                            that.doOpenChooseTimeCancel();
                        }
                    }
                })
            }

            //计算时长
            if (that.ChooseStartModel.timetitle != undefined && that.ChooseEndModel.timetitle != undefined) {
                var ReservationDate = moment(that.SelectTime).format("YYYY-MM-DD");
                var newDate1 = ReservationDate + ' ' + that.ChooseStartModel.timetitle;
                var newDate2 = ReservationDate + ' ' + that.ChooseEndModel.timetitle;
                const date1 = moment(newDate1);
                const date2 = moment(newDate2);
                var DelayTimeDiff = date2.diff(date1, 'm');
                let hours = Math.floor(DelayTimeDiff / 60);
                let minutes = DelayTimeDiff % 60;
                that.CalculateTimeDesc = hours + '小时' + minutes + '分钟';
                if (DelayTimeDiff < 0) {
                    that.CalculateTimeDesc = "";
                    that.doOpenChooseTimeCancel();
                }
            }

        },
        //会议服务选择
        doOpenChooseService() {
            this.IsShowService = !this.IsShowService;
        },
        onChooseService() {
        },
        onCountTotalPrice() {
            var that = this;
            that.TotalPrice = 0;
            if (that.ServiceList.length > 0) {
                var countPrice = 0;
                that.ServiceList.forEach((item, index, array) => {
                    if (item.Number > 0) {
                        countPrice += item.Number * item.UnitPrice;
                    }
                });
                that.TotalPrice = countPrice.toFixed(2);
            }
        },
        onClickServiceDel(item) {
            item.Number = 0;
        },
        //临时物品选择
        doOpenChooseItem() {
            this.IsShowItem = !this.IsShowItem;
        },
        doSelectCloseItem(item) {
            item.IsSelected = false;
            //this.form.ItemList.splice(this.form.ItemList.indexOf(item), 1);
        },
        onChooseItem(item) {
            item.IsSelected = !item.IsSelected;
        },
        do_save() {
            var that = this;
            if (that.form.MeetingTitle <= 0) {
                api.toast({
                    msg: '请填写会议主题',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (!that.form.StartTime || !that.form.EndTime) {
                api.toast({
                    msg: '请选择预约时段',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (!that.form.MeetingApplyPhone) {
                api.toast({
                    msg: '请填写申请人电话',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (!/^[1]\d{10}$/.test(that.form.MeetingApplyPhone)) {
                api.toast({
                    msg: '请输入正确的申请人电话',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }

            var options = {};
            options.action = 'savemeetingreservation';
            options.ProjectID = that.ProjectID;
            options.MeetingRoomID = that.MeetRoomID;
            options.MeetingTitle = that.form.MeetingTitle;
            options.MeetingApplyPhone = that.form.MeetingApplyPhone;
            options.ReservationDate = that.form.ReservationDate;
            options.ReservationStartTime = that.form.StartTime;
            options.ReservationEndTime = that.form.EndTime;
            options.Description = that.form.Descriotion;
            options.Remark = that.form.Remark;
            options.MeetingPeopleNum = that.form.MeetingPeopleNum;

            var ItemList = that.ItemList.filter((val) => {
                return val.IsSelected == true;
            });
            var ServiceList = that.ServiceList.filter((val) => {
                return val.Number > 0;
            });
            options.MeetingItemList = JSON.stringify(ItemList);
            options.MeetingServiceList = JSON.stringify(ServiceList);

            //console.log('savevisit-options=>', options);
            ns.post(options, function (succeed, data, err) {
                //console.log('savevisit=>',data);
                if (data.status) {
                    api.toast({
                        msg: "操作成功",
                        duration: 2000,
                        location: 'bottom'
                    });
                    api.sendEvent({
                        name: 'reloadmeetlist',
                    });
                    api.sendEvent({
                        name: 'reloadmeetservicelist',
                    });
                    setTimeout(function () {
                        api.closeWin();
                    }, 300)
                }
                else if (data.error) {
                    api.toast({
                        msg: data.error,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
                else if (data.Msg) {
                    api.toast({
                        msg: data.Msg,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
                else {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }
            })

        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    dialog = new auiDialog();
    toast = new auiToast();
    imageBrowser = api.require('imageBrowser');

    app.MeetRoomID = api.pageParam.ID || 0;
    app.ProjectID = api.pageParam.ProjectID || 0;
    app.get_data();

    if (app.ProjectID) {
        app.get_data_item();
        app.get_data_service();
    }
};
